<?php

namespace App\Http\Controllers\Manage;

use App\Http\Requests;
use App\Model\Designer;
use App\Model\Product;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;

use App\Model\ClientCase;
use App\Model\ProductCategory;
use App\Model\Picture;
use App\Model\CaseAttachment;
use App\Model\Industry;
use App\Model\CasePicture;
use Illuminate\Validation\Rules\In;

class ClientCaseController extends Controller
{
    protected static $field = [
        ['id'=>1,'searchtype'=>'编号'],
        ['id'=>2,'searchtype'=>'创建时间'],
        ['id'=>3,'searchtype'=>'案例编号'],
        ['id'=>4,'searchtype'=>'案例名'],
        ['id'=>5,'searchtype'=>'行业'],
        ['id'=>6,'searchtype'=>'场景'],
//        ['id'=>7,'searchtype'=>'类别'],
        ['id'=>8,'searchtype'=>'产品'],
        ['id'=>9,'searchtype'=>'设计师'],
        ['id'=>10,'searchtype'=>'价格'],
        ['id'=>11,'searchtype'=>'制作时间'],
        ['id'=>12,'searchtype'=>'制作单位'],
    ];

    /**
     * 案例列表
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index() {
        $search = Input::get('searchtype');
        $param = Input::get('param');
        $start_time = Input::get('start_time');
        $end_time = Input::get('end_time');
        $count = Input::get('count');
        $page = Input::get('page');
        $orderBy = Input::get('orderBy');
        $ind = Input::get('ind');
        $pro = Input::get('pro');
//        dump(input::all());

        if (empty($start_time)){
            $start_time = "0000-00-00 00:00:00";
        }
        if (empty($end_time)){
            $end_time = date("Y-m-d H:i:s",time());
        }
        $obj = new ClientCase;
        #判断时间
        if (!empty($start_time)){
            $obj = $obj->where('update_time','>=',$start_time);
        }
        if (!empty($end_time)){
            $obj = $obj->where('update_time','<=',$end_time);
        }
        #判断关键字
        $id = array();
        if($search == 1){
            $obj = $obj->where('id','like',"%$param%");
        }elseif ($search == 2){
            $obj = $obj->where('create_time','like',"%$param%");
        }elseif ($search == 3){
            $obj = $obj->where('number','like',"%$param%");
        }elseif ($search == 4){
            $obj = $obj->where('name','like',"%$param%");
        }elseif ($search == 5){
            $industry = Industry::where('name','like',"%$param%")->get();
            foreach ($industry as $i) {
                $id[] = $i['id'];
            }
            $obj = $obj->whereIn('industry',$id);
        }elseif ($search == 6){
            if($param == '线上'){
                $pa = 0;
            }elseif($param == '线下') {
                $pa = 1;
            }
            $obj = $obj->where('scene','like',"%$pa%");
        }elseif ($search == 7){
            $category = ProductCategory::where('name','like',"%$param%")->get();
            foreach ($category as $i) {
                $id[] = $i['id'];
            }
            $obj = $obj->whereIn('category',$id);
        }elseif ($search == 8){
            $product = Product::where('name','like',"%$param%")->get();
            foreach ($product as $i) {
                $id[] = $i['id'];
            }
            $obj = $obj->whereIn('product_id',$id);
        }elseif ($search == 9){
            $des = Designer::select('id')->where('name','like',"%$param%")->get();
            $obj = $obj->whereIn('designer',$des);
        }elseif ($search == 10){
            $obj = $obj->where('price','like',"%$param%");
        }elseif ($search == 11){
            $obj = $obj->where('make_time','like',"%$param%");
        }elseif ($search == 12){
            $obj = $obj->where('producer','like',"%$param%");
        }elseif ($search == 100){
            $obj = $obj->where('status',$param);
        }
        if(!empty($ind)){
            $obj = $obj->where('industry',$ind);
        }
        #判断产品类型
        $u = null;
        if(!empty($pro)) {
            $u = explode('-',$pro);
            if($u[0] == 1){
                $s = ProductCategory::find($u[1]);
                if($s['level'] == 1) {
                    $x = ProductCategory::where('parent_id',$u[1])->get();
                    foreach ($x as $value) {
                        $z[] = $value['id'];
                    }
                    $obj = $obj->whereIn('category',$z);
                }
                else {
                    $obj = $obj->where('category',$u[1]);
                }
            }
            if($u[0] == 2) {
                $obj = $obj->where('product_id',$u[1]);
            }
        }
        #判断时间排序
        if($orderBy == 1){
            $obj = $obj->orderBy('update_time','ASC');
        }elseif($orderBy == 2){
            $obj = $obj->orderBy('update_time','DESC');
        }else{
            $obj = $obj->orderBy('rank','DESC')->orderBy('update_time','DESC');
        }
        $list = $obj->Paginate(15);
        if(empty($page)){
            $count = $obj->count();
        }
        if($list == false && !empty($search)){
            return redirect()->back()->withSuccess('未搜索到结果！');
        }
        #获取行业信息
        $industry = Industry::getAll();
        #获取产品一级分类
        $product = ProductCategory::getOneInfo();
        foreach ($product as $o => $one) {
            $product[$o]['two'] = ProductCategory::getOneTwoInfo($one['id']);
            foreach ($product[$o]['two'] as $t => $two) {
                $product[$o]['two'][$t]['pro'] = Product::getCategoryInfo($two['id']);
            }
        }
        $searchtype = self::$field;
        return view('manage.case.index',[
            'list'=>$list,
            'searchtype'=>$searchtype,
            'search'=>$search,
            'param'=>$param,
            'orderBy'=>$orderBy,
            'start_time'=>$start_time,
            'end_time'=>$end_time,
            'ind' =>$ind,
            'pro' => $pro,
            'count'=>$count,
            'industry'=>$industry,
            'product'=>$product,
            'active1'=>6,
            'active2'=>1
        ]);
    }

    /**
     * 添加案例
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function caseAdd() {
        $ind = Industry::where('status',1)->get();
        $category = ProductCategory::where('status',1)->where('level',1)->get();
        $product = Product::where('status',1)->get();
        $designer = Designer::where('status',1)->get();
        return view('manage.case.caseAdd', ['ind'=>$ind,'category'=>$category,'product'=>$product,'designer'=>$designer,'active1'=>6,'active2'=>2]);
    }

    /**
     * 获取二级联动数据
     * @param $id
     */
    public function classes($id){
//        $grade = input::get('id');
        $classes=ProductCategory::where("parent_id",$id)->where('status',1)->get();
        echo json_encode($classes);
    }

    /**
     * @param $cate
     * @return mixed
     */
    public function three($cate) {
        $product = Product::where('category',$cate)->where('status',1)->get();
        return $product;
    }

    /**
     * 提交案例
     * @return string
     */
    public function create() {
        $res = null;
        $number = rand(10000000,99999999);
        $name = input::get('name');
        $industry = input::get('industry');
        $scene = input::get('scene');
        $category = input::get('grade');
        $category_son = input::get('classes');
        $product_id = input::get('product_id');
        $designer = input::get('designer');
        $marketer = input::get('marketer');
        $price = input::get('price');
        $producer = input::get('producer');
        $make_time = input::get('make_time');
        $rank = input::get('rank');
        $url = input::get('url');
        $keyword = input::get('keyword');
        $brief = input::get('brief');
        $lable = input::get('lable');
        $content = input::get('content');
        $case_edit = input::get('case_edit');
        $icon = input::file('file');
        $cover = input::get('cover');


        if(empty($name)) {
            $res = [
                'code' => 103,
                'msg' => '名字不能为空!',
                'num' => ""
            ];
            return json_encode($res);
        }
        $map = ClientCase::where('name',$name)->first();
        if(!empty($map)) {
            $res = [
                'code' => 102,
                'msg' => '案例名已存在!',
                'num' => ""
            ];
            return json_encode($res);
        }
        $store = ClientCase::insert([
            'number' => $number,
            'name' => $name,
            'industry' => $industry,
            'scene' => $scene,
            'category' => $category_son,
            'product_id' => $product_id,
            'designer' => $designer,
            'marketer' => $marketer,
            'price' => $price,
            'producer' => $producer,
            'make_time' => $make_time,
            'rank' => $rank,
            'location' => $url,
            'keyword' => $keyword,
            'brief' => $brief,
            'lable' => $lable,
            'content' => $content,
            'edit' => $case_edit,
            'cover' => $cover
        ]);
        if($store) {
            $res = [
                'code' => 100,
                'msg' => '添加成功!',
                'num' => $number
            ];
        }
        else {
            $res = [
                'code' => 101,
                'msg' => '添加失败!',
                'num' => ""
            ];
        }
        return json_encode($res);
    }

    /**
     * 获取案例ID
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id) {

//        $pic_name = null;
//        #设置oss参数
//        $ossClient = $this->oss();
//        try {
//            $listObjectInfo = $ossClient->listObjects($this->bucket);
//            $objectList = $listObjectInfo->getObjectList();
//            if (!empty($objectList)) {
//                foreach ($objectList as $objectInfo) {
////                    print($objectInfo->getKey() . "\t!" . $objectInfo->getSize() . "\t!" . $objectInfo->getLastModified() . "\n||");
//                    $pic_name[] = $objectInfo->getKey();
//                }
//            }
//        } catch (OssException $e) {
//            print $e->getMessage();
//        }
//        $pic = null;
//        $picture = CasePicture::whereIn('name',$pic_name)->where('link_id',$id)->where('category',0)->get()->toArray();
//        foreach($picture as $p => $k ) {
//            $picture[$p]['url'] = "http://".$this->bucket.".".$this->point."/".$k['name'];
//        }

        $case = ClientCase::where('id',$id)->first();
        $cate_son = ProductCategory::where('id',$case->category)->first();
        $cate_sons = ProductCategory::where('parent_id',$cate_son['parent_id'])->get();
        $ind = Industry::where('status',1)->get();
        $product = Product::where('status',1)->get();
        $designer = Designer::where('status',1)->get();
        $category = ProductCategory::where('status',1)->where('level',1)->get();
//        $annex = CaseAttachment::where('link_id',$id)->where('category',0)->get()->toArray();
        return view('manage.case.caseEdit', ['ind'=>$ind,'category'=>$category,'product'=>$product,'case'=>$case,'designer'=>$designer,'cate_son'=>$cate_son,'cate_sons'=>$cate_sons,'active1'=>6,'active2'=>1]);
    }

    /**
     * 更新案例
     * @return string
     */
    public function update() {
        $res = null;
        $id = input::get('id');
        $data['name'] = input::get('name');
        $data['industry'] = input::get('industry');
        $data['scene'] = input::get('scene');
        $data['category'] = input::get('classes');
//        $data['category_son'] = input::get('classes');
        $data['designer'] = input::get('designer');
        $data['marketer'] = input::get('marketer');
        $data['product_id'] = input::get('product_id');
        $data['price'] = input::get('price');
        $data['producer'] = input::get('producer');
        $data['make_time'] = input::get('make_time');
        $data['rank'] = input::get('rank');
        $data['location'] = input::get('url');
        $data['keyword'] = input::get('keyword');
        $data['brief'] = input::get('brief');
        $data['lable'] = input::get('lable');
        $data['content'] = input::get('content');
        $data['edit'] = input::get('case_edit');
        if(input::get('cover')){
            $data['cover'] = input::get('cover');
        }


        if(empty($data['name'])) {
            $res = [
                'code' => 103,
                'msg' => '名字不能为空!'
            ];
            return json_encode($res);
        }

        $update= ClientCase::where('id',$id)->update($data);
        if($update) {
            $res = [
                'code' => 100,
                'msg' => '更新成功!'
            ];
        }
        else {
            $res = [
                'code' => 101,
                'msg' => '更新失败!'
            ];
        }
        return json_encode($res);
    }

    /**
     * 载入上传页
     * @param $num
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function upload($num) {
        $case = ClientCase::where('number',$num)->first();
        $cate_son = ProductCategory::where('status',1)->where('id',$case->category)->first();
        $ind = Industry::where('status',1)->get();
        $category = ProductCategory::where('status',1)->where('level',1)->get();
        return view('manage.case.upload', ['ind'=>$ind,'category'=>$category,'case'=>$case,'cate_son'=>$cate_son,'active1'=>6,'active2'=>1]);
    }

    /**
     * 上传图片
     * @return array|null
     */
    public function picture() {
        $res = null;
        #设置oss参数
        $ossClient = $this->oss();

        $id = input::get('picture_id');
//        $name = input::get('name');
        $content = input::get('brief');
        $rank = input::get('rank');
        $url = input::get('path');
        $name = preg_replace('/.*\//','',$url);
        if(empty($name) || empty($content)) {
            try {
                $ossClient->deleteObject($this->bucket, $url);
            } catch (OssException $e) {
//                        print $e->getMessage();
            }
            $res = [
                'code' => 101,
                'msg' => "缺少元素!"
            ];
            return $res;
        }
        $success = null;

        $map = CasePicture::insert(['link_id' => $id,'rank'=>$rank,'name' => $name,'content'=>$content,'path'=> $url,'category'=>0]);
        if ($map) {
            $res = [
                'code' => 100,
                'msg' => "上传成功!"
            ];
        } else {
            try {
                $ossClient->deleteObject($this->bucket, $url);
            } catch (OssException $e) {
//                        print $e->getMessage();
            }
            $res = [
                'code' => 102,
                'msg' => "上传失败!"
            ];
        }
        return $res;
    }

    /**
     * 修改图片文字描述
     * @return array
     */
    public function setContent()
    {
        $content = Input::get('content');
        $id = Input::get('id');
        CasePicture::where('id',$id)->update(['content'=>$content]);
        return [
            'code'=>100,
            'msg'=>'修改成功！'
        ];
    }

    public function setRank() {
        $rank = Input::get('rank');
        $id = Input::get('id');
        CasePicture::where('id',$id)->update(['rank'=>$rank]);
        return [
            'code'=>100,
            'msg'=>'修改成功！'
        ];
    }

    /**
     * 上传附件
     * @return array|null
     */
    public function annex() {
        $res = null;
        #设置oss参数
        $ossClient = $this->oss();

        $id = input::get('annex_id');
        $rank = input::get('rank');
        $url = input::get('path');
        $name = preg_replace('/.*\//','',$url);
//        dump($rank);
//        dump($id);
//        dump($name);
//        $brief = input::get('brief');
        if(empty($name)) {
            try {
                $ossClient->deleteObject($this->bucket, $url);
            } catch (OssException $e) {
//                        print $e->getMessage();
            }
            $res = [
                'code' => 101,
                'msg' => '缺少元素!'
            ];
            return $res;
        }

            $map = CaseAttachment::insert(['link_id' => $id,'rank'=>$rank,'name' => $name,'path'=> $url,'category'=>0]);
            if ($map) {
                $res = [
                    'code' => 100,
                    'msg' => "上传成功!"
                ];
            } else {
                try {
                    $ossClient->deleteObject($this->bucket, $url);
                } catch (OssException $e) {
//                        print $e->getMessage();
                }
                $res = [
                    'code' => 102,
                    'msg' => "上传失败!"
                ];
            }
        return $res;
    }

    /**
     * 启用、禁用
     * @return array
     */
    public function caseStatus() {
        $id = Input::get('id');
        $status = Input::get('status');
        if($status == 1) {
            $del = ClientCase::where('id',$id)->update(['status'=>1]);
            $msg = '启用成功！';
        }else{
            $del = ClientCase::where('id',$id)->update(['status'=>0]);
            $msg = '禁用成功！';
        }
        if(!$del){
            return [
                'code'=>101,
                'msg'=>'设置失败！'
            ];
        }
        return [
            'code'=>100,
            'msg'=>$msg
        ];
    }

    /**
     * 图片管理
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function casePicture($id) {
        $case = ClientCase::where('id',$id)->first();
        $picture = CasePicture::where('link_id',$id)->where('category',0)->orderBy('rank','desc')->get();
        return view('manage.case.pictureEdit',['case'=>$case,'picture'=>$picture,'active1'=>6,'active2'=>1]);
    }

    //删除图片
    public function deletePicture() {
        $id = input::get('id');
        $path = input::get('path');
        $res = null;

        #设置oss参数
        $ossClient = $this->oss();
        $del = CasePicture::where('id',$id)->delete();
        if($del) {
            $res = [
                'code' => 100,
                'msg' => '删除成功!'
            ];
            try {
                $ossClient->deleteObject($this->bucket, $path);
            } catch (OssException $e) {
//                        print $e->getMessage();
            }
        }
        else {
            $res = [
                'code' => 101,
                'msg' => '删除失败!'
            ];
        }
        return $res;
    }

    /**
     * 启禁用图片
     * @return array
     */
    public function pictureStatus() {
        $id = Input::get('id');
        $status = Input::get('status');
        if($status == 1) {
            $del = CasePicture::where('id',$id)->update(['status'=>1]);
            $msg = '启用成功！';
        }else{
            $del = CasePicture::where('id',$id)->update(['status'=>0]);
            $msg = '禁用成功！';
        }
        if(!$del){
            return [
                'code'=>101,
                'msg'=>'设置失败！'
            ];
        }
        return [
            'code'=>100,
            'msg'=>$msg
        ];
    }

    /**
     * 附件管理
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function caseAnnex($id) {
        $case = ClientCase::where('id',$id)->first();
        $annex = CaseAttachment::where('link_id',$id)->where('category',0)->orderBy('rank','desc')->get();
        return view('manage.case.annexEdit',['case'=>$case,'annex'=>$annex,'active1'=>6,'active2'=>1]);
    }

    /**
     * 删除附件
     * @param $id
     * @param $name
     * @return array|null
     */
    public function deleteAnnex() {
        $id = input::get('id');
        $path = input::get('path');
        $res = null;

        #设置oss参数
        $ossClient = $this->oss();
//        $url = CaseAttachment::find($id)['path'];
        $del = CaseAttachment::where('id',$id)->delete();
        if($del) {
            $res = [
                'code' => 100,
                'msg' => '删除成功!'
            ];
            try {
                $ossClient->deleteObject($this->bucket, $path);
            } catch (OssException $e) {
//                        print $e->getMessage();
            }
        }
        else {
            $res = [
                'code' => 101,
                'msg' => '删除失败!'
            ];
        }
        return $res;
    }

    /**
     * 启禁用附件
     * @return array
     */
    public function annexStatus() {
        $id = Input::get('id');
        $status = Input::get('status');
        if($status == 1) {
            $del = CaseAttachment::where('id',$id)->update(['status'=>1]);
            $msg = '启用成功！';
        }else{
            $del = CaseAttachment::where('id',$id)->update(['status'=>0]);
            $msg = '禁用成功！';
        }
        if(!$del){
            return [
                'code'=>101,
                'msg'=>'设置失败！'
            ];
        }
        return [
            'code'=>100,
            'msg'=>$msg
        ];
    }

    public function caseShow($id) {
        $case = ClientCase::where('id',$id)->first();
        $pic = CasePicture::where('link_id',$id)->get()->toArray();
        $att = CaseAttachment::where('link_id',$id)->get()->toArray();
        return view('manage.case.caseShow',['case'=>$case,'pic'=>$pic,'att'=>$att,'active1'=>6,'active2'=>1]);
    }
    /**
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function seo($id)
    {
        #获取对应案例seo信息
        $seo = ClientCase::where('id',$id)->select('id','name','title','keyword','description')->first();
        return view('manage.case.seo',compact('seo'));
    }

    public function setSeo()
    {
        $id = Input::get('id');
        $data['title'] = Input::get('title');//标题
        $data['keyword'] = Input::get('keyword');//关键字
        $data['description'] = Input::get('description');//描述
        #获取对应案例信息
        $case = ClientCase::where('id',$id)->first()->toArray();
        foreach ($case as $k=>$v){
            $data['title'] = str_replace("{".$k."}",$v,$data['title']);
            $data['keyword'] = str_replace("{".$k."}",$v,$data['keyword']);
            $data['description'] = str_replace("{".$k."}",$v,$data['description']);
        }

//        $data['title'] = str_replace("{".array_keys($case,$case['title'])."}",$case['title'],$title);

        if(ClientCase::where('id',$id)->update($data)){
            return [
                'code'=>$data,
                'msg'=>'修改成功！'
            ];
        }else{
            return [
                'code'=>101,
                'msg'=>'修改失败！'
            ];
        }
    }

}
